local skynet = require "skynet"

local s = require "service"
local agent_player = require "agent_player"
local agent_def = require "agent_def"
local protobuf_helper = require "protobuf_helper"
local table_utils = require "table_utils"

require "agent_resp_client"


-- 目前一个账号只有一个role，所以在这里用agent加载role数据

s.init = function()
    s.player = agent_player.new()
    -- load玩家数据
    local isok, player_data = skynet.call("mysql_node", "lua", "query_player_data", s.id)

    if not isok then
        skynet.error("load player data error, uid:" .. s.id)
        -- TODO: 如何处理
        return
    end

    -- 基础信息
    s.player:set_uid(s.id)
    s.player:set_nickname(player_data.nickname)
    s.player:set_exp(player_data.exp)
    s.player:set_gold(player_data.gold)
    s.player:set_diamond(player_data.diamond)

    -- 战斗属性
    local fight_info = protobuf_helper.decode(agent_def.PROTO_TYPE_FIGHT_INFO, player_data.fight_info)
    if fight_info then
        s.player:set_fight_info(fight_info)
    end
    -- 场景位置属性
    local scene_info = protobuf_helper.decode(agent_def.PROTO_TYPE_SCENE_INFO, player_data.scene_info)
    if scene_info then
        s.player:set_scene_id(scene_info.scene_id)
        s.player:set_scene_gid(scene_info.scene_gid)
        s.player:set_position(scene_info.position)
    end

    -- 背包
    -- 技能
    -- 任务

    s.player:set_status(agent_def.PLAYER_STATUS.LOGIN)
end


s.resp.kick = function(source)
    -- 离开场景
    skynet.error(s.id .. "退出, 开始离开场景")
    local scene_node = s.player:get_scene_node()
    if scene_node and scene_node > 0 then
        local isok, new_scene_info = skynet.call(scene_node, "lua", "request_leave", s.player:get_uid())
        return
    end
    
    skynet.error(s.id .. "退出时没有进入场景")
end

s.resp.exit = function(source)
    if s.is_exiting then
        return
    end
    s.is_exiting = true

    -- 保存数据
    skynet.error(s.id .. "退出, 保存数据")

    -- 退出自身
    skynet.exit()
end


s.start(...)